package queue_stack.queue.impl;

import queue_stack.queue.Queue;

import java.util.NoSuchElementException;

/**
 * 循环队列实现
 * tail == front -> 队列空
 * (tail + 1) % data.length == front -> 队列满
 * @param <E>
 */
public class LoopQueue<E> implements Queue<E> {
    private int size;
    // front指向当前循环队列的队首，tail指向当前队列的最后一个元素的下一个索引
    private int front,tail;
    private E[] data;

    /**
     * 由于循环队列会浪费一个空间，因此初始化数组大小为容量 + 1
     * @param capacity 初始化容量
     */
    public LoopQueue(int capacity) {
        this.data = (E[]) new Object[capacity + 1];
    }

    public LoopQueue() {
        this(10);
    }

    /**
     * 容量为数组长度 - 1
     * @return 当前队列容量
     */
    public int getCapacity() {
        return data.length - 1;
    }



    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new NoSuchElementException("队列为空");
        }
        E result = data[front];
        front = (front + 1) % data.length;
        size --;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return result;
    }

    @Override
    public E getFont() {
        if (isEmpty()) {
            throw new NoSuchElementException("队列为空");
        }
        return data[front];
    }

    @Override
    public void enqueue(E e) {
        // 判断当前队列是否已满
        if ((tail + 1) % data.length == front) {
            // 扩容
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size ++;
    }

    /**
     * resize操作
     * @param newCapacity 调整后的数组大小
     */
    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity + 1];
        for (int i = 0; i < this.size; i++) {
            // 新数组的索引下标相对原数组有front的偏移
            newData[i] = data[(i + front) % data.length];
        }
        data = newData;
        // 还原front和tail的指向
        front = 0;
        tail = size;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return tail == front;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("LoopQueue:size = %d,capacity = %d\n",size,getCapacity()));
        sb.append("front [");
        for (int i = front; i != tail; i = (i + 1) % data.length) {
            sb.append(data[i]);
            if ((i + 1) % data.length != tail) {
                sb.append(",");
            }
        }
        sb.append("] tail");
        return sb.toString();
    }

    public static void main(String[] args) {
        LoopQueue<Integer> queue = new LoopQueue<>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);

            if (i % 3 == 2) {
                queue.dequeue();
                System.out.println(queue);
            }
        }
    }
}
